<template>
  <div class="login">
    <info
      :ruleForm="contextInfo"
      @on-behavior="onLogin"
      @refreshVerify="refreshVerify"
    />
  </div>
</template>

<script lang="ts">
interface Data {
  token: string;
  name: string;
}

import { reactive, onBeforeMount } from "vue";
import { ReturnDTO } from "/@/api/type";
import info, { ContextProps, CaptchaDTO } from "../components/ReInfo/index.vue";
import { getVerify, getLogin } from "/@/api/user";
import { useRouter } from "vue-router";
import { storageSession } from "/@/utils/storage";
import { warnMessage, successMessage } from "/@/utils/message";
export default {
  name: "login",
  components: {
    info
  },
  setup() {
    const router = useRouter();

    // 刷新验证码
    const refreshGetVerify = async () => {
      let returnDTO = (await getVerify()) as ReturnDTO;
      let response: CaptchaDTO = returnDTO.response;
      contextInfo.key = response.key;
      contextInfo.svg = "data:image/jpeg;base64," + response.image;
    };

    const contextInfo: ContextProps = reactive({
      userName: "",
      passWord: "",
      verify: null,
      svg: null,
      key: null
    });

    const toPage = (info: Object): void => {
      storageSession.setItem("info", info);
      router.push("/");
    };

    // 登录
    const onLogin = async () => {
      let { userName, passWord, verify, key } = contextInfo;
      let response: ReturnDTO = await getLogin({
        username: userName,
        password: passWord,
        verify: verify,
        key: key
      });
      let date: Data = response.response;
      contextInfo.verify = "";
      response.code === 1
        ? successMessage(response.message) &&
          toPage({
            username: date.name,
            accessToken: date.token
          })
        : warnMessage(response.message) && refreshVerify();
    };

    const refreshVerify = (): void => {
      refreshGetVerify();
    };

    onBeforeMount(() => {
      refreshGetVerify();
    });

    return {
      contextInfo,
      onLogin,
      router,
      toPage,
      refreshVerify
    };
  }
};
</script>
